package com.wekri.wechat4j.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author liuweiguo
 */
public class WeChatTokenManager {

    RedisTemplate<String, String> redisTemplate;

    Logger logger = LoggerFactory.getLogger(WeChatTokenManager.class);

    public WeChatTokenManager(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public String getToken(String appId) {
        return redisTemplate.opsForValue().get("wekri:" + appId + ":token");
    }

    public String getTicket(String appId) {
        return redisTemplate.opsForValue().get("wekri:" + appId + ":ticket");
    }

    public void updateToken(String weChatAppId, String weChatAppSecret) {
        logger.info("更新微信公众号:[{}]token", weChatAppId);

        AccessToken accessToken = new AccessToken(weChatAppId, weChatAppSecret);
        if (accessToken.request()) {
            redisTemplate.opsForValue().set("wekri:" + weChatAppId + ":token", accessToken.getAccess_token(), 2, TimeUnit.HOURS);
            logger.info("微信公众号:[{}]获取token成功，token:{}",
                    weChatAppId, accessToken.getAccess_token());

            Ticket ticket = new Ticket(accessToken.getAccess_token());
            if (ticket.request()) {
                redisTemplate.opsForValue().set("wekri:" + weChatAppId + ":ticket", ticket.getTicket(), 2, TimeUnit.HOURS);
                logger.info("微信公众号:[{}]获取JsapiTicket成功，JsapiTicket:{}",
                        weChatAppId, ticket.getTicket());
            } else {
                logger.error("微信公众号:[{}]获取JsapiTicket失败", weChatAppId);
            }
        } else {
            logger.error("微信公众号:[{}]获取token失败", weChatAppId);
        }
    }
}
